package com.genymobile.scrcpy.five.cmd;

import android.os.SystemClock;
import android.view.KeyEvent;

import com.genymobile.scrcpy.five.inject.FiveInjector;

public class FiveKeyEventCmd extends ICmd {

    private int displayId;
    private int action;

    private int keyCode;
    private int repeat;
    private int metaState;

    public static FiveKeyEventCmd convert(KeyEvent event, int displayId) {
        FiveKeyEventCmd cmd = new FiveKeyEventCmd();
        cmd.timestampMs = SystemClock.elapsedRealtime();
        cmd.keyCode = event.getKeyCode();
        cmd.action = event.getAction();
        cmd.repeat = event.getRepeatCount();
        cmd.metaState = event.getMetaState();
        cmd.displayId = displayId;
        return cmd;
    }

    @Override
    public boolean run(FiveInjector injector) {
        return injector.injectKeyEvent(action, keyCode, repeat, metaState, displayId);
    }

    @Override
    ICmd parse(long timestampMs, String[] arr) {
        FiveKeyEventCmd event = new FiveKeyEventCmd();
        event.timestampMs = timestampMs;

        int i = 0;
        event.displayId = Integer.parseInt(arr[i++]);
        event.action = Integer.parseInt(arr[i++]);
        event.keyCode = Integer.parseInt(arr[i++]);
        event.repeat = Integer.parseInt(arr[i++]);
        event.metaState = Integer.parseInt(arr[i++]);
        return event;
    }

    @Override
    String getCmdName() {
        return "key";
    }

    @Override
    public String toString() {
        return super.toString() + displayId
                + " " + action
                + " " + keyCode
                + " " + repeat
                + " " + metaState
                + " " + (action == KeyEvent.ACTION_DOWN ? " #### key down": "#### key up");
    }
}
